package com.local.order.rabbitmq;


import com.local.common.constants.OrderStatusEnum;
import com.local.order.constants.OrderConstants;
import com.local.order.pojo.Order;
import com.local.order.service.OrderService;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * RabbitMq队列消费者。监听队列，在收到消息时，对消息进行处理
 */
@Component
public class RabbitMqConsumer {

    @Autowired
    private OrderService orderService;

    //@RabbitListener(queues = "simple.queue") //当队列不存在时，不会自动创建队列，而且会报错。
    @RabbitListener(queuesToDeclare = @Queue(OrderConstants.orderUnpayDeadLetterQueue)) //当队列不存在时，自动创建队列
    public void orderUnPayDeadLetterConsumer(String orderNo) {
        System.out.println("orderUnPayDeadLetterConsumer 接收消息orderNo: "+orderNo);
        if (Objects.nonNull(orderNo) && orderNo.length() > 0) {
            Order order = orderService.getByOrderNo(orderNo);
            //如果订单的状态是“未支付”，则取消该订单
            if (Objects.nonNull(order) && order.getOrderStatus() == OrderStatusEnum.TO_PAY.getValue()) {
                orderService.timeOutClose(order.getOrderId());
                System.out.println("orderUnPayDeadLetterConsumer处理结束: "+orderNo);
            }
        }
    }
}
